﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EntityFrameworkCore
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly AuditDbContext _auditDbContext = null;

        private static ConcurrentDictionary<string, DbContext> _cache =
     new ConcurrentDictionary<string, DbContext>();
        private static ThreadLocal<string> _threadLocal= new ThreadLocal<string>();

 
        public UnitOfWork(AuditDbContext auditDbContext)
        {
     
            _auditDbContext = auditDbContext;
            //BeginTran();
        }

        public  string CreatInstance()
        {
          
            var key = Guid.NewGuid().ToString().Replace("-", "");
            if (!_cache.ContainsKey(key))
            {
                _cache.TryAdd(key, (_auditDbContext as DbContext));
                _threadLocal.Value = key;
            }

            return key;
            //SqlSugarClient client = new SqlSugarClient(new ConnectionConfig()
            //{
            //    ConnectionString = _connStr, //必填
            //    DbType = DbType.MySql, //必填
            //    IsAutoCloseConnection = true, //默认false
            //    InitKeyType = InitKeyType.SystemTable
            //});
            //var key = Guid.NewGuid().ToString().Replace("-", "");
            //if (!_cache.ContainsKey(key))
            //{
            //    _cache.TryAdd(key, new SqlClient(client));
            //    _threadLocal.Value = key;
            //    return client;
            //}
            //throw new Exception("创建SqlSugarClient失败");
        }

        public DbContext GetInstance()
        {
            var id = _threadLocal?.Value;
            if (string.IsNullOrEmpty(id) || !_cache.ContainsKey(id))
               id= CreatInstance();
            return _cache[id];
        }


        public  string GetId()
        {
            var id = _threadLocal.Value;
            return id;
        }

        public bool HasCommited { get; private set; }
        public  void BeginTran()
        {
            if (GetId() != null)
            {
                return;
            }
            
            //开启事务
            var instance = GetInstance();
            instance.Database.BeginTransaction();
        }
        public void Commit()
        {
            var id = GetId();
            if (!_cache.ContainsKey(id))
                throw new Exception("内部错误: SqlSugarClient已丢失.");
            
            try
            {
                _cache[id].Database.CommitTransaction();
                _cache.TryRemove(id,out DbContext dbContext);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
